﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VOL.demo.IServices.wms.ReturnOrder;
using VOL.Entity.DomainModels;

namespace VOL.WebApi.Controllers.demo
{
    [Route("api/[controller]")]
    [ApiController]
    public class ReturnOrderController : ControllerBase
    {
      
        private readonly IReturnOrderIServices _returnOrderService;

        public ReturnOrderController(IReturnOrderIServices returnOrderService)
        {
            _returnOrderService = returnOrderService;
        }

        /// <summary>
        /// 分页查询退货单（包含供应商名称、部门名称、客户名称）
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns>分页结果</returns>
        [HttpGet("page")]
        public async Task<IActionResult> GetPageList(int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                // 修改为调用联查方法，默认就包含关联信息
                var result = await _returnOrderService.GetPageListWithRelationsAsync(pageIndex, pageSize);
                return Ok(new 
                { 
                    Code = 200, 
                    Data = result.Data, 
                    TotalCount = result.TotalCount,
                    Message = "查询成功"
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 根据ID获取退货单
        /// </summary>
        /// <param name="id">退货单ID</param>
        /// <returns>退货单信息</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetById(long id)
        {
            try
            {
                var result = await _returnOrderService.GetByIdAsync(id);
                if (result == null)
                {
                    return NotFound(new { Code = 404, Message = "未找到该退货单" });
                }
                
                return Ok(new { Code = 200, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 更新退货单
        /// </summary>
        /// <param name="entity">退货单实体</param>
        /// <returns>更新结果</returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromBody] returnordermodel entity)
        {
            try
            {
                if (entity == null || entity.Id <= 0)
                {
                    return BadRequest(new { Code = 400, Message = "无效的退货单数据" });
                }
                
                var result = await _returnOrderService.UpdateAsync(entity);
                if (result)
                {
                    return Ok(new { Code = 200, Message = "更新成功" });
                }
                else
                {
                    return BadRequest(new { Code = 400, Message = "更新失败" });
                }
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"更新失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 删除退货单
        /// </summary>
        /// <param name="id">退货单ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(long id)
        {
            try
            {
                var result = await _returnOrderService.DeleteAsync(id);
                if (result)
                {
                    return Ok(new { Code = 200, Message = "删除成功" });
                }
                else
                {
                    return BadRequest(new { Code = 400, Message = "删除失败，可能该退货单不存在或已审核" });
                }
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"删除失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 批量删除退货单
        /// </summary>
        /// <param name="ids">退货单ID列表</param>
        /// <returns>删除结果</returns>
        [HttpDelete("batch")]
        public async Task<IActionResult> BatchDelete([FromBody] long[] ids)
        {
            try
            {
                if (ids == null || ids.Length == 0)
                {
                    return BadRequest(new { Code = 400, Message = "请选择要删除的退货单" });
                }
                
                var result = await _returnOrderService.DeleteRangeAsync(ids);
                if (result)
                {
                    return Ok(new { Code = 200, Message = "批量删除成功" });
                }
                else
                {
                    return BadRequest(new { Code = 400, Message = "批量删除失败" });
                }
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"批量删除失败: {ex.Message}" });
            }
        }
        
        /// <summary>
        /// 获取进货单联查列表（包含供应商名称、部门名称、客户名称）
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns>分页结果</returns>
        [HttpGet("purchaseOrders")]
        public async Task<IActionResult> GetPurchaseOrderList(int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var result = await _returnOrderService.GetPurchaseOrderListAsync(pageIndex, pageSize);
                return Ok(new 
                { 
                    Code = 200, 
                    Data = result.Data, 
                    TotalCount = result.TotalCount,
                    Message = "查询成功"
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }
        
        /// <summary>
        /// 根据进货单编号获取进货单信息（包含供应商、联系人、联系方式、部门、进货人）
        /// </summary>
        /// <param name="orderCode">进货单编号</param>
        /// <returns>进货单信息</returns>
        [HttpGet("purchaseOrder/code/{orderCode}")]
        public async Task<IActionResult> GetPurchaseOrderByCode(string orderCode)
        {
            try
            {
                if (string.IsNullOrEmpty(orderCode))
                {
                    return BadRequest(new { Code = 400, Message = "进货单编号不能为空" });
                }
                
                var result = await _returnOrderService.GetPurchaseOrderByCodeAsync(orderCode);
                if (result == null)
                {
                    return NotFound(new { Code = 404, Message = "未找到该进货单" });
                }
                
                return Ok(new { Code = 200, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }
        
        /// <summary>
        /// 根据进货单号获取进货明细列表（包含货品信息）
        /// </summary>
        /// <param name="orderCode">进货单号</param>
        /// <returns>进货明细列表</returns>
        [HttpGet("purchaseOrder/code/{orderCode}/items")]
        public async Task<IActionResult> GetPurchaseOrderItemsByCode(string orderCode)
        {
            try
            {
                if (string.IsNullOrEmpty(orderCode))
                {
                    return BadRequest(new { Code = 400, Message = "进货单号不能为空" });
                }
                
                var result = await _returnOrderService.GetPurchaseOrderItemsByCodeAsync(orderCode);
                return Ok(new { Code = 200, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取退货单联查结果（包含供应商名称、部门名称、客户名称）
        /// </summary>
        /// <param name="id">退货单ID</param>
        /// <returns>退货单联查结果</returns>
        [HttpGet("withRelations/{id}")]
        public async Task<IActionResult> GetWithRelations(long id)
        {
            try
            {
                var result = await _returnOrderService.GetWithRelationsAsync(id);
                if (result == null)
                {
                    return NotFound(new { Code = 404, Message = "未找到该退货单" });
                }
                
                return Ok(new { Code = 200, Data = result, Message = "查询成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 分页查询退货单联查结果（包含供应商名称、部门名称、客户名称）
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns>分页结果</returns>
        [HttpGet("pageWithRelations")]
        public async Task<IActionResult> GetPageListWithRelations(int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var result = await _returnOrderService.GetPageListWithRelationsAsync(pageIndex, pageSize);
                return Ok(new 
                { 
                    Code = 200, 
                    Data = result.Data, 
                    TotalCount = result.TotalCount,
                    Message = "查询成功"
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Code = 500, Message = $"查询失败: {ex.Message}" });
            }
        }
        /// <summary>
        /// 添加退货单和退货明细（使用事务）
        /// </summary>
        /// <param name="createDto">退货单和退货明细创建DTO，不包含系统字段</param>
        /// <returns>添加结果</returns>
        [HttpPost("withDetails")]
        public async Task<IActionResult> AddWithDetails([FromBody] ReturnOrderWithDetailsCreateDto createDto)
        {
            try
            {
                Console.WriteLine("=== Controller开始处理 ===");
                Console.WriteLine($"createDto是否为null: {createDto == null}");
                
                if (createDto == null)
                {
                    Console.WriteLine("❌ 失败原因: createDto为null");
                    return BadRequest(new { Code = 400, Message = "请求数据为空" });
                }
                
                if (createDto.ReturnOrder == null)
                {
                    Console.WriteLine("❌ 失败原因: ReturnOrder为null");
                    return BadRequest(new { Code = 400, Message = "退货单信息为空" });
                }
                
                if (createDto.ReturnOrderDetails == null || !createDto.ReturnOrderDetails.Any())
                {
                    Console.WriteLine("❌ 失败原因: ReturnOrderDetails为空");
                    return BadRequest(new { Code = 400, Message = "退货明细为空" });
                }

                Console.WriteLine("✅ Controller验证通过，调用Service");
                var result = await _returnOrderService.AddWithDetailsAsync(createDto);
                Console.WriteLine($"Service返回结果: {result}");
                
                if (result)
                {
                    Console.WriteLine("✅ 添加成功");
                    return Ok(new { Code = 200, Message = "添加成功" });
                }
                else
                {
                    Console.WriteLine("❌ Service返回false，添加失败");
                    return BadRequest(new { Code = 400, Message = "添加失败" });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ Controller异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return BadRequest(new { Code = 500, Message = $"添加失败: {ex.Message}" });
            }
        }
    }
}